<?php
namespace jy_weishop\order;
defined('BY_JYA') or exit('error');
/*
	配送费
*/
class dada_api extends \plugin{
	/**
     * 签名生成signature
     */
	public function dada_sign($data, $app_secret)
	{
		ksort($data);
		$args = '';

		foreach ($data as $key => $value) {
			$args .= $key . $value;
		}

		$args = $app_secret . $args . $app_secret;
		$sign = strtoupper(md5($args));
		return $sign;
	}

	/**
     * 构造请求数据
     * data:业务参数，json字符串
     */
	public function dada_bulidRequestParams($data, $app_key, $source_id, $app_secret)
	{
		$requestParams = array();
		$requestParams['app_key'] = $app_key;
		$requestParams['source_id'] = $source_id;
		$requestParams['body'] = json_encode($data);
		$requestParams['format'] = 'json';
		$requestParams['v'] = '1.0';
		$requestParams['timestamp'] = time();
		$requestParams['signature'] = $this->dada_sign($requestParams, $app_secret);
		return $requestParams;
	}

	/**
     * 获取达达的配送城市信息
     */
	public function getdadacity()
	{
		$url = 'https://newopen.imdada.cn/api/cityCode/list';
		$app_key = '';
		$source_id = '72971';
		$app_secret = '';
		$reqParams = $this->dada_bulidRequestParams('', $app_key, $source_id, $app_secret);
		$resp = cfc('http')->ihttp_request($url, json_encode($reqParams), array('Content-Type' => 'application/json'));
		$ret = @json_decode($resp['content'], true);
		if($ret['status']!='success'){
			exi('达达更新商户异常'.$ret['msg'],'error');				
		}
		return $ret;
	}
	/**
     * 添加门店
     */
	public function addshop($merch=array())
	{
		$url = 'https://newopen.imdada.cn/api/shop/add';
		$cityexpress = $this->plugin_setting('citypeisong');
		$app_key = $cityexpress['dd_app_key'];
		$app_secret = $cityexpress['dd_app_secret'];
		$source_id = $cityexpress['dd_source_id'];
		if(!$cityexpress['dd_business']){
			exi('达达创建商户异常,后台同城配送--未设置【物品品类ID】','error');
		}
		$merch['lat_lng']=json_decode($merch['lat_lng'],true);
		$data=array();
		$shop = array(
			'station_name' => $merch['merchname'],
			'business' => $cityexpress['dd_business'],
			'station_address' => $merch['address'],
			'lng' => $merch['lat_lng']['lng'],
			'lat' => $merch['lat_lng']['lat'],
			'contact_name' => $merch['realname'],
			'phone' => $merch['mobile'],
		);
		$data[]=$shop;
		$reqParams = $this->dada_bulidRequestParams($data, $app_key, $source_id, $app_secret);
		$resp = cfc('http')->ihttp_request($url, json_encode($reqParams), array('Content-Type' => 'application/json'));
		$ret = @json_decode($resp['content'], true);
		if($ret['status']!='success'){
			exi('达达创建商户异常'.$ret['msg'],'error');				
		}
		return $ret['result']['successList'];
	}
	public function upshop($merch=array())
	{
		$url = 'https://newopen.imdada.cn/api/shop/update';
		$cityexpress = $this->plugin_setting('citypeisong');
		$app_key = $cityexpress['dd_app_key'];
		$app_secret = $cityexpress['dd_app_secret'];
		$source_id = $cityexpress['dd_source_id'];
		$merch['lat_lng']=json_decode($merch['lat_lng'],true);
		$data = array(
			'station_name' => $merch['merchname'],
			'origin_shop_id' => $merch['dd_shop_id'],
			'station_address' => $merch['address'],
			'lng' => $merch['lat_lng']['lng'],
			'lat' => $merch['lat_lng']['lat'],
			'contact_name' => $merch['realname'],
			'phone' => $merch['mobile'],
		);
		$reqParams = $this->dada_bulidRequestParams($data, $app_key, $source_id, $app_secret);
		$resp = cfc('http')->ihttp_request($url, json_encode($reqParams), array('Content-Type' => 'application/json'));
		$ret = @json_decode($resp['content'], true);
		return $ret;
	}
	public function cancel_send($order_id,$cancel_reason_id=0,$cancel_reason=''){
		$url = 'https://newopen.imdada.cn/api/order/formalCancel';
		$cityexpress = $this->plugin_setting('citypeisong');
		$app_key = $cityexpress['dd_app_key'];
		$app_secret = $cityexpress['dd_app_secret'];
		$source_id = $cityexpress['dd_source_id'];
		$ordersn=pdo_getcolumn('jy_weishop_order',array('id'=>$order_id,'uniacid'=>$_SESSION['uniacid']),'ordersn');
		$data = array(
			'order_id' => $ordersn,
			'cancel_reason_id' => $cancel_reason_id?:4,
			'cancel_reason' => $cancel_reason,
		);
		$reqParams = $this->dada_bulidRequestParams($data, $app_key, $source_id, $app_secret);
		$resp = cfc('http')->ihttp_request($url, json_encode($reqParams), array('Content-Type' => 'application/json'));
		$ret = @json_decode($resp['content'], true);
		if ($ret['code'] == 0) {
			return array('state' => 1, 'msg' => '取消成功');
		}
		return array('state' => 0, 'msg' => $ret['msg']);
	}
	public function dada_send($order,$merchid=0)
	{
		$url = 'https://newopen.imdada.cn/api/order/addOrder';
		$cityexpress = $this->plugin_setting('citypeisong');
		if (!empty($cityexpress)) {
			if ($cityexpress['express_type'] == 3) {
				$app_key = $cityexpress['dd_app_key'];
				$app_secret = $cityexpress['dd_app_secret'];
				$source_id = $cityexpress['dd_source_id'];
				if($merchid){
					$myshop=pdo_get('jy_merch_user',array('id'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
					$cityexpress['pcd']=json_decode($myshop['pcd'],true);
					if(!$myshop['dd_shop_id']){
						$successList=$this->addshop($myshop);
						$myshop['dd_shop_id']=$successList[0]['originShopId'];
						if($myshop['dd_shop_id']){
							pdo_update('jy_merch_user',array('dd_shop_id'=>$myshop['dd_shop_id']),array('id'=>$merchid,'uniacid'=>$_SESSION['uniacid']));
						}
					}
					$cityexpress['dd_shop_id']=$myshop['dd_shop_id'];
				}
				$shop_id = $cityexpress['dd_shop_id'];
				if(!$shop_id){
					exi('达达那边未找到相关门店！','error');
				}
				$city_code = pdo_getcolumn('core_area',array('address'=>$cityexpress['pcd']['province'].' '.$cityexpress['pcd']['city'].' '.$cityexpress['pcd']['district']),'code');
                if($order['address'] && ($order['address']['address'] || $order['address']['mobile'])){
                    $receiver=$order['address'];
                }else{
                    $receiver=pdo_get('core_address',array('id'=>$order['addressid'],'uniacid'=>$_SESSION['uniacid']));
                }
                if(!is_array($receiver['pcd'])){
                    $receiver['pcd']=json_decode($receiver['pcd'],true);
                }
				$addressinfo=$receiver['pcd']['province'] . $receiver['pcd']['city'] . $receiver['pcd']['district'] . $receiver['pcd']['street'] . $receiver['address'];
				$location_data = cfc('tools')->getgeocode($addressinfo, $cityexpress['geo_key']);
				if ($location_data['status'] == 1 && 0 < $location_data['count']) {
					$location = explode(',', $location_data['geocodes'][0]['location']);
					$data = array(
						'shop_no' => $shop_id,
						'city_code' => $city_code,
						'origin_id' => $order['ordersn'],
						'info' => $order['remark'],
						'cargo_price' => $order['price'],
						'receiver_name' => $receiver['name'],
						'receiver_address' => $addressinfo,
						'receiver_phone' => $receiver['mobile'],
						'receiver_lng' => $location[0],
						'receiver_lat' => $location[1],
						'is_prepay' => 0,
						'expected_fetch_time' => time() + 600,
						'callback' => SITEROOT.'/addons/jy_weishop/notify/dada_order.php'
					);
					$reqParams = $this->dada_bulidRequestParams($data, $app_key, $source_id, $app_secret);
					$resp = cfc('http')->ihttp_request($url, json_encode($reqParams), array('Content-Type' => 'application/json'));
					$ret = @json_decode($resp['content'], true);
					if ($ret['code'] == 0) {
						return array('state' => 1, 'msg' => '发货成功');
					}
					return array('state' => 0, 'msg' => $ret['msg']);
				}
				return array('state' => 0, 'msg' => '获取收件人坐标失败，请检查收件人地址:'.$addressinfo);
			}
			return array('state' => 1, 'msg' => '发货成功');
		}
		return array('state' => 0, 'msg' => '参数异常');
	}
}